var footer = $('#footer').removeAttr('id').clone(); 
var headpic = $('.head_pic').eq(0).clone();
//jqm创建页面后的操作
$('body').on('pagecreate', '.ui-page', function(){
    //解析与过滤emoji表情
    if((!supportEmoji)&&(typeof twemoji != 'undefined')){
        twemoji.size='16x16'    
        twemoji.parse(this, {
            callback: function(icon, options, variant) {
                switch ( icon ) {
                    case 'a9':      // © copyright
                    case 'ae':      // ® registered trademark
                    case '2122':    // ™ trademark
                        return false;
                }
                return ''.concat(options.base, options.size, '/', icon, options.ext);
            }
        });
    }
    //自动增加网页页头与页脚
    var temp = $(this);
    var header = temp.children('[data-role="header"]')
    if(temp.find('footer').length==0){
        temp.append(footer.clone());
    }
    if(headpic.length&&temp.find('.head_pic').length==0){
        console.info(this)
        temp1 = temp
        header.after(headpic.clone());
    }
    //优酷视频的大小调整
    $('.youku').load(function(){
        $(this).height($(this).width()*0.8);
    })
    //通过判断是否解锁按钮
    if(ifwxsuccess){
        $('.chooseimages, #fwscan').removeClass('ui-disabled');
    }

    //调整图片描述与图片的长度
    temp.find('.decimgsrc').load(function(){
        var self = $(this)
        var imgdec = self.prev('.imgdec')
        // console.info(self, imgdec, this.width)
        if(imgdec.text()==""){
            imgdec.hide()
        }else{
            imgdec.css('max-width', this.width-2+'px')
        }
    })    

})

var wx_logo_bak, wx_logo_url = $('#wx_logo img').attr('src');
//jqm页面展现后的操作
$('body').on('pageshow', '.ui-page', function(){
    // console.info('pageshow', this)
    //微信公众号logo加载
    var wx_logo = $(this).find('.wx_logo');
    if(wx_logo.length!=0){
        wx_logo_bak = $('#wx_logo').html()
        wx_logo_url = wx_logo.find('img').attr('src')
        $('#wx_logo').html(wx_logo.html())
    }else{
        wx_logo_url = $('#wx_logo img').attr('src');
    }
    //判断是否使用微信客户端与微信公众号功能准备完毕,则更新微信功能
    if(inwx&&wxready){
        refreshwechat(this);
    }      
})
$('body').on('pagebeforeshow', '.ui-page', function(){
    // console.info('pagebeforeshow', this)
})
$('body').on('pagehide', '.ui-page', function(){
    // console.info('pagehide', this)
})
$('body').on('pagebeforecreate', '[data-role=page]', function(){
    // console.info('pagebeforecreate', this);
    //判断是否使用微信客房端与微信公众号功能准备完毕,若是,则进行公众号功能修复
    if(inwx&&wxready&&this.hasAttribute('wechatsignused')){
        fixpage(this);
    }
    //设置备份图片的大小
    $('img.decimgsrc').load(function(){
        self = $(this)
        selfcopy = self.clone()
        selfcopy.removeClass('style')
        w = selfcopy[0].width, h = selfcopy[0].height
        console.info('load:', w + 'x' + h)
        self.attr('img-size', w + 'x' + h)
        selfcopy.remove()
    })
    //调整地图大小
    $('#map iframe').load(function(){
            $(this).show()
            $.mobile.loading('hide')
            $(this).height($('footer').offset().top - $(this).offset().top)
            $(this).width($(this).parent().width()) //for android2.3 100%width bug
    })
    //调整防伪大小
    $('#fwquery iframe').load(function(){
            $(this).show()
            $.mobile.loading('hide')
            $(this).height($('#fwquery footer').offset().top - $(this).offset().top)
            $(this).width($(this).parent().width()) //for android2.3 100%width bug
    })
    //防伪输入mask
    var fwvalue = $('#fwcode').val()
    $('#fwcode').mask('9999-9999-9999-9999')
    //增加自动输入防伪
    if(fwvalue){
        newfwvalue = ''
        var i
        for(i=0;i<3;i++){
            newfwvalue += fwvalue.slice(i*4, i*4+4) + '-'
        }
        newfwvalue += fwvalue.slice(i*4, i*4+4)
        $('#fwcode').val(newfwvalue)
    }
})
//jmq页面隐藏前的操作
$('body').on('pagebeforehide', '.ui-page', function(){
    // console.info('beforehide', this)
    var wx_logo = $(this).find('.wx_logo');
    if(wx_logo.length!=0 && wx_logo_bak !=null){
        $('#wx_logo').html(wx_logo_bak)
    }
})
//增加首页按钮
if(!$('#home').length){
    $('[data-role="page"]:not([id="home"], [id="postsid"])').eq(0).find('header').append('<a href="." rel="external" class="ui-btn-left" data-icon="home" data-iconpos="notext">Home</a>');
}
$('#postsid header').append('<a href="memberposts" class="ui-btn-left" rel="external" data-role="button" data-icon="back" class="ui-btn-right">分享区</a>')
//初始化class external的按鈕
// $('.external').attr('rel', 'external');

var images1 = ['http://ss.bdimg.com/static/superman/img/logo/bd_logo1_31bdc765.png',
'http://img5.imgtn.bdimg.com/it/u=3750695734,1192334129&fm=21&gp=0.jpg',
'http://img5.imgtn.bdimg.com/it/u=3750695734,1192334129&fm=21&gp=0.jpg',
'http://img5.imgtn.bdimg.com/it/u=3750695734,1192334129&fm=21&gp=0.jpg',
'http://img5.imgtn.bdimg.com/it/u=3750695734,1192334129&fm=21&gp=0.jpg',
'http://img0.imgtn.bdimg.com/it/u=751865090,564508156&fm=21&gp=0.jpg']

var images = {
    localId: [],
    // serverId: [],
    // uploadedId: [],
};

var imgdec
addpreimage = function(items){
    var $div = $('.imagespreview')
    // $div.empty()  //清空已经选图片
    for(i=0;i<items.length;i++){
        var picpre = $('<div class="picpre"><img src="'
            +items[i]+
            '"><div class="addimgdec"></div><br/>'+
            '<a href="#" class="delete">删除</a> '+
            '<a href="#" class="adddes">描述</a></img></div>')  
        $div.append(picpre);
        //绑定预览图片删除键
        picpre.find('.delete').bind('click', function(){
            var parent = $(this).parent();
            // var link = parent.find('img').attr('src');
            // var index = items.indexOf(link)
            // if(index!=-1){ items.splice(index, 1); };
            //注释以上三行改成以下一行
            images.localId.splice(parent.index(), 1);
            parent.remove();
        })
        //绑定预览图片描述键
        picpre.find('.adddes').bind('click', function(){
            imgdec = $(this).siblings('.addimgdec')
            imgdesdialog(this, imgdec)
        })    
    }
}
$('body').on('click', '.chooseimages', function(){
    //addpreimage(images)
    chooseimage(images, addpreimage);
})
$('body').on('change', '#title', function(event, ui) {
   if($(this).val()!=""){
        $('[type=submit]').button('enable');
   }else{
        $('[type=submit]').button('disable');
   } 
});

//属性为nohash链接去除history的返回键
// $('body').on('click', '.nohash', function(){
    // console.info(this)
    // $.mobile.loadPage('postweb')
    // $.mobile.changePage('postweb', {'changeHash': false})
    // return false;
// })

//微信选择图片功能  
chooseimage = function(items, handle){
    $.mobile.loading('show');
    wx.chooseImage({
        count: 9, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
            // items.localId = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片 
            items.localId = items.localId.concat(res.localIds) //直接添加到原localId中
            handle(res.localIds);
            $.mobile.loading('hide');
            $('.chooseimages .ui-btn-text').text('继续选择');
        },
        cancel: function(){
            $.mobile.loading('hide');
        }
    });
}
//微信上传图片功能
uploadimage = function(items){
    // alert('上传图片item为' + items.localId)
    if(items.localId.length==0){
        mydialog($('input[type=submit]'), '请选择图片后再上传!');
        return;}
    var i = 0, length = items.localId.length
    var serverIds = [];
    upload = function(){
        wx.uploadImage({
            localId: items.localId[i],
            success: function(res){
                $('.delete').eq(i).text('上传成功').unbind('click');
                i++;
                serverIds.push(res.serverId);
                if(i<length){
                    upload(); 
                }else{
                    $.mobile.loading('show');
                    submitpost(serverIds);
                }
            }
        })
    }
    upload();
    
}

//formpost 提交键绑定   
$('body').on('click', '#submit', function(){
    var imagesids = uploadimage(images);
    return false;
})
submitpost = function(imageids){
    imgdecs = $('.addimgdec').map(function(){return $(this).text()}).get();
    imgdecs = escape(JSON.stringify(imgdecs).replace(/%u/g, '%25u'))
    $.post('postweb', 
        $('form').serialize()+'&imageids='+imageids+'&imgdecs='+imgdecs, 
        function(data){
            $.mobile.loading('hide');
            if(data=='done'){
                // alert('上传成功');
                mydialog($('input[type=submit]'), '上传成功', function(){window.location.replace('memberposts')});
            }else if(data=='postalready'){
                mymessage('抱歉,活动投票类型仅可发布一次')
            }else if(data=='VoteEnd'){
                mymessage('本投票活动已经结束，感谢您的参与')              
            }else if(data=='nosession'){
                myauthdialog($('input[type=submit]'));
            }else{
                // alert('上传失败');
                mydialog($('input[type=submit]'), '上传失败');
            }
        }   
    )     
}

//临时信息显示提示框
mymessage = function(text){
    $.mobile.loading('show', {'text': text, 'textonly': true, 'textVisible': true, 'theme': 'a'})
    setTimeout('$.mobile.loading("hide")', 1500);
}

//确定提示框
mydialog = function(element, buttonPrompt, okfunc){
    if(okfunc==null){okfunc=function(){};}
    element.simpledialog2({
    mode: 'button',
    headerText: '温馨提示',
    buttonPrompt: buttonPrompt,
    themeDialog: 'c',
    // dialogForce: true,
    // showModal: true,    
    buttons : {
      '确定': {
        click: okfunc,
      },
    }
  })
}
//要求授权提示框
myauthdialog = function(self){
    mydialog(self, '您还未登录<br/>按确定键返回绑定微信授权', 
        function(){location.replace('auth2?goto=memberposts')});
}

//图片描述输入框
imgdesdialog = function(e, imgdec){
   $('body').simpledialog2({
    mode: 'blank',
    headerText: '输入图片描述',
    buttonInput: true,
    headerClose: true,
    forceInput: false,
    callbackOpen: function(){
        $('#dsubmit').bind('click', function(){
            console.info($('.inputimgdes input').val())
            console.info($(e).parent())
            imgdec.text($('.inputimgdes input').val());
        })
    },
    blankContent:
        '<div class="inputimgdes"><input value="'+ imgdec.text() +'"/>'+      
        '<a id="dsubmit" rel="close" href="#" data-role="button" data-icon="check">确定</a>'+
        '</div>'
   })    
}
//评论输入框
mytextdialog = function(){
   $('body').simpledialog2({
    mode: 'blank',
    headerText: '评论内容',
    buttonInput: true,
    headerClose: true,
    forceInput: true,
    callbackOpen: function(){
        // $('#dsubmit').bind('click', function(){
            // console.info($('#comment').val())
        // })
    },
    blankContent:
        '<form class="textareacomment"><textarea name="c_content" id="comment" placeholder="评论内容"></textarea>'+      
        '<a class="postcomment" rel="close" href="#" data-inline="true" data-role="button" data-icon="check">确定</a>'+
        '</form>'
   })
}
$('body').on('click', '.getcomment a', function(){
    mytextdialog();
})
// $('body').on('click', '#dsubmit', function(){
    // console.info(imgdec)
    // imgdec.text($('.inputimgdes input').val());
// })

//判断是否需要解析emoji表情
var supportEmoji = false, inwx = false, UA = navigator.userAgent;
if (UA.match(/Mac\s+OS/i) && !UA.match(/(Chrome|Firefox)/i)) {
    supportEmoji = true;
}
if(UA.search('MicroMessenger')!=-1){
    inwx = true;
}

//通过去除jqm加载页面的data-url,解决与微信公众号功能的兼容性
fixpage = function(self){
    $self = $(self);
    if($self.attr('data-external-page') == "true"){
        $self.attr('data-bak-url', $self.attr('data-url'));
        // $self.attr('data-url', 'fixforwechat&'+Math.random().toString(36).substring(7));
        $self.attr('data-url', 'fixforwechat'+$self.attr('data-url').replace(/[\/?]/g, '&'))
    }
}

//wechat绑定朋友圈与好友分享时的资料
wechatshare = function(title, imgurl, link, des){
    // var title = "分享测试标题"
    if(!des){des = "音速风暴"}
    // var imgurl = $.mobile.path.makeUrlAbsolute('/static/images/wx_logo.jpg')
    var imgurl = $.mobile.path.makeUrlAbsolute(imgurl)    
    // var link = 'http://www.baidu.com'
    var link = $.mobile.path.makeUrlAbsolute(link)        
    //分享到朋友圈
    wx.onMenuShareTimeline({
        title: title, 
        link: link, 
        imgUrl: imgurl, 
        success: function(){
            // alert('朋友圈'+'分享成功')
            // 此处埋点
            $.post('manage?action=wxshareTimeline&link='+link)
        },
        cancel: function(){alert('朋友圈'+'分享取消')},
    });
    //分享给朋友
    wx.onMenuShareAppMessage({
        title: title,
        desc: des,
        link: link,
        imgUrl: imgurl,
        type: '', // 分享类型,music、video或link，不填默认为link
        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
        success: function(){
            // alert('微信朋友'+'分享成功')
            // 此处埋点
            $.post('manage?action=wxshareAppMesage&link='+link)            
        },
        cancel: function(){alert('微信朋友'+'分享取消')},
    });
    //分享到QQ
    wx.onMenuShareQQ({
        title: title, // 分享标题
        desc: des, // 分享描述
        link: link, // 分享链接
        imgUrl: imgurl, // 分享图标
        success: function(){alert('QQ好友'+'分享成功')},
        cancel: function(){alert('QQ好友'+'分享取消')},
    });
    //分享到QQ微博
    wx.onMenuShareWeibo({
        title: title, // 分享标题
        desc: des, // 分享描述
        link: link, // 分享链接
        imgUrl: imgurl, // 分享图标
        success: function(){alert('QQ微博'+'分享成功')},
        cancel: function(){alert('QQ微博'+'分享取消')},
    });
    //分享到QQ空间
    wx.onMenuShareQZone({
        title: title, // 分享标题
        desc: des, // 分享描述
        link: link, // 分享链接
        imgUrl: imgurl, // 分享图标
        success: function(){alert('QQ空间'+'分享成功')},
        cancel: function(){alert('QQ空间'+'分享取消')},
    });    
}

//初始化微信配置
var wxconfig = {}, wxconfigset = false, wxready = false;
if($(document).find('.wx_data').length==1){
    $('.wx_data input').each(function(i, e){
        wxconfig[e.name] = e.value;
    })    
    wxconfig.debug = false; //debug 开关
    wxconfig.jsApiList = [
        'checkJsApi', 'chooseImage', 'uploadImage', 'hideMenuItems', 
        'onMenuShareAppMessage', 'onMenuShareTimeline', 'onMenuShareQQ',
        'onMenuShareWeibo', 'onMenuShareQZone', 'previewImage', 'scanQRCode',
    ];
    wxconfigset = true
}
var ifwxsuccess = false 
//更新微信的功能设置
refreshwechat = function(self){
    var title = $('title').text()
    var imgurl = wx_logo_url;
    var link;
    if($(self).attr('data-bak-url')=='undefined'){
        link = location.href;
    }else{
        link = $(self).attr('data-bak-url')
    }
    var des = $(self).attr('wx-des')
    if(des){
       wechatshare(title, imgurl, link, des); 
    }else{
        wechatshare(title, imgurl, link);
    }
}
//初始化并解锁与分享
if(wxconfigset){
    wx.config(wxconfig);
    wx.ready(function(){
        // wx.hideMenuItems({
            // menuList: ['menuItem:copyUrl', 'menuItem:originPage', 
            // 'menuItem:openWithQQBrowser', 'menuItem:openWithSafari']
        // });
        wx.checkJsApi({
            jsApiList: ['chooseImage', 'uploadImage', 'scanQRCode'],
            success: function(res){
                ifwxsuccess = true;
                $('.chooseimages, #fwscan').removeClass('ui-disabled');
            },
        });
        wxready = true;
        refreshwechat($('[data-role=page]')[0]);
    });
}

//删贴按钮绑定
$('body').on('click', '.delpost,.c_delbtn', function(){
    // console.info(this);
    self = $(this)
    if(self.hasClass('c_delbtn')){
        btntype = '评论'
        clickfunc = function(){deletcomment(self)}
    }else{
        btntype = '贴'
        clickfunc = function(){deletpost(self)}
    }
    self.simpledialog2({
    mode: 'button',
    headerText: '温馨提示',
    buttonPrompt: '确认删除此'+btntype+'?<br/>点确认删'+btntype+',点其它位置取消返回',
    themeDialog: 'c',
    forceInput: false,    
    buttons : {
      '确定': {
        click: clickfunc,
      },
    }
  })    

})
deletpost = function(self){
    $.mobile.loading('show')
    var pid = self.parent().find('.ui-link-inherit').attr('href').split('pid=')[1]
    $.post('manage?action=delpost', {'pid': pid}).done(function(data){
        console.info(data);
        if(data=='delsuccess'){
            var parent = self.parent()
            var ul = self.parents('ul')
            var divider = parent.prevAll(".ui-li-divider").eq(0)
            var count = parseInt(divider.children('span.ui-li-count').text())
            if(count>1){
                divider.children('span.ui-li-count').text(--count)
            }else{
                divider.remove()
            }
            parent.remove();
            ul.listview('refresh');
        }
        $.mobile.loading('hide')
    })    
}
//删除评论绑定
deletcomment = function(self){
    $.mobile.loading('show')
    pid = self.attr('c_pid')
    $.post('manage?action=delcomment', {'pid': pid}).done(function(data){
        console.info(data)
        if(data=='delsuccess'){
            self.parents('.c_item').remove()
        }
        $.mobile.loading('hide')
    })
}

//点赞按钮绑定
$('body').on('click', '.getlike', function(e){
    self = $(this)
    // self.addClass('ui-disabled')
    // self.removeClass('getlike')
    pid = self.parents('.ui-page').attr('data-bak-pid')
    $.post('manage?action=getlike', {'pid': pid})
    .done(function(data){
        console.info(data);
        if(data=='nosession'){
            mymessage('未登录用户无法点赞');
            self.removeClass('ui-disabled')
        }else if(data=='nosessionOpenid'){
            mymessage('请从公众号进入本页面, 或在分享区登录后进入');
            self.removeClass('ui-disabled')            
        }else if(data=='Done'){
            // getlikefunc(e);
            self.addClass('heartAnimation')
            var getlikecount = parseInt(self.next().text())+1
            // self.next().text(getlikecount)
            self.parents('.ui-page').find('.likecount,.likeCount').text(getlikecount)
            refreshgetlike(self, getlikecount)
            // self.parent().html('<span>已赞</span>')   
        }else if(data=='AlreadyLike'){
            mymessage('此贴您已点过赞');
            self.css('background-position', 'right')
            // self.parent().html('<span>已赞</span>') 
        }else if(data=='AlreadyLikeVote'){
            mymessage('你今日已投过票，请明天再来投票吧')
            self.css('background-position', 'right') 
        }else if(data=='VoteEnd'){
            mymessage('本投票活动已经结束，感谢您的参与')           
        }else{
            mymessage('未知错误');
        }
    })
    // getlikefunc(e);
    // self.parent().html('<span>已赞</span>')
})
//更新点赞数
refreshgetlike = function(self, getlikecount){
    var page = self.parents('.ui-page')
    var pid = page.attr('data-bak-pid')
    var postscount = $('a[href$="pid='+pid+'"]').parent().find('.ui-li-count')
    postscount.text(postscount.text().replace(/\d+/, getlikecount))
    
}
//点赞数字动画
getlikefunc = function(e){
    var x = e.pageX, y = e.pageY
    var i = $('<b>').text('+1')
    i.css({'top': y-20, 'left': x+10, 'position': 'absolute'})
    $('body').append(i)
    i.animate({top: y-100, opacity:0, "font-size": "3em"}, 1000, function(){
        i.remove()
    });
}
//评论框获焦点时显示评论按键
$('body').on('focus', 'textarea.comment', function(){
    self = $(this);
    self.next().show();
})
$('body').on('click', 'a.cancelcomment', function(){
    self = $(this);
    t = self.parent().prev();
    t.val("")
    self.parent().hide();
})
$('body').on('click', 'a.postcomment', function(){
    var self = $(this);
    self.addClass('ui-disabled')
    $.mobile.loading('show');
    form = self.parents('form')
    var pid = self.parents('.ui-page').attr('data-bak-pid')
    $.post('manage?action=postcomment&pid='+pid, form.serialize(), null, 'json')
    .done(function(data){
        $.mobile.loading('hide');
        console.info(data)
        refreshcomment(data.comments)
        $('.commentit').hide()
        $('textarea.comment').val("")
        self.removeClass('ui-disabled')
    }).fail(function(data){
        console.info(data.responseText);
        $.mobile.loading('hide');
        self.removeClass('ui-disabled')        
        if(data.responseText=='nosession'){
            myauthdialog(self);
        }else{
        // mydialog(self, '未知错误:'+data.responseText+'<br/>请重试');
        mymessage('未知错误:' + data.responseText)
        }
        
    })
})

//添加评论按钮绑定
// $('body').on('click', '.getcomment', function(e){
    // var x = e.pageX, y = e.pageY
    // $('#popupcomment').popup('open', {x: x-20, y: y-20})
// })

//加载更新评论
refreshcomment = function(comments){
    var c_items = $('.c_items')
    c_items.empty();
    for(i=0;i<comments.length;i++){
        c_item = getcomment(comments[i])
        c_items.append(c_item)
    }
}
getcomment = function(comment){
    c_item = $('<div class="c_item"><div class="author">'+
        '<img src="'+comment.headimgurl+'"/><div><strong>'+comment.author+'</strong></div>'+
        '</div><div class="c_item_content">'+comment.c_content+
        '</div><div class="c_item_date">'+comment.c_item_date+'</div><hr/></div>')
    return c_item
}

//选择分类绑定
$('body').on('change', '.postselect select', function(){
    console.info(this)
    self = $(this)
    ul = self.parents('.ui-page').find('ul')
    ul.find('li').show()
    var label = this.value
    if(this.value!='all'){
        ul.find('li.padsmall:not([data-bak-label='+label+'])').hide();
    }
    ul.find('li.ui-li-divider').each(function(){
        var divider = $(this)
        var i = 0
        divider.nextUntil('li.ui-li-divider').each(function(){
            if($(this).attr('style')!='display: none;'){i++;}
        })
        if(i==0){divider.hide();}
        else{divider.children('span.ui-li-count').text(i)}
    })
    ul.listview('refresh');
})

//photoswipe方法
openPhotoswipe = function(element, self_url){
    pswpElement = $('.pswp')[0]
    var items = [], urls = []
    element.find('img.decimgsrc').each(function(){
        var self = $(this)
        item = {
            src: self.attr('src'),
            w: parseInt(self.attr('img-size').split('x')[0]),
            h: parseInt(self.attr('img-size').split('x')[1]),
            title: self.prev().text()
        }
        items.push(item)
        urls.push(self.attr('src'))
    })
    i = urls.indexOf(self_url)
    console.info(items)
    var options = {
        history: false,
        focus: false,
        index: i,
        showAnimationDuration: 0,
        hideAnimationDuration: 0
    }
    var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options)
    gallery.init();
}
//photoswipe綁定
$(document).on('click', 'img.decimgsrc', function(){
    var self = $(this)
    var page = self.parents('.ui-page')
    console.info(page)
    if(UA.search('MicroMessenger/6')!=-1&&wxready&&page[0].hasAttribute('wechatsignused')){
        openPhotoPreviewsInWx(page, self.attr('src'))
        //埋点测试
        $.post('manage?action=photoswipe_inwx');        
    }else{
        openPhotoswipe(page, self.attr('src'))
        //埋点测试
        $.post('manage?action=photoswipe');
    }
})
//微信jssdk图片预览
openPhotoPreviewsInWx = function(page, self_url){
    wx.previewImage({
        current: self_url, // 当前显示图片的http链接
        urls: page.find('img.decimgsrc').map(function(){return this.src}).get() // 需要预览的图片http链接列表
    });
}
//photowipe模版插入
$('<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true"><div class="pswp__bg"></div><div class="pswp__scroll-wrap"><div class="pswp__container"><div class="pswp__item"></div><div class="pswp__item"></div><div class="pswp__item"></div></div><div class="pswp__ui pswp__ui--hidden"><div class="pswp__top-bar"><div class="pswp__counter"></div><button class="pswp__button pswp__button--close" title="Close (Esc)"></button><button class="pswp__button pswp__button--share" title="Share"></button><button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button><button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button><div class="pswp__preloader"><div class="pswp__preloader__icn"><div class="pswp__preloader__cut"><div class="pswp__preloader__donut"></div></div></div></div></div><div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap"><div class="pswp__share-tooltip"></div></div><button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"></button><button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"></button><div class="pswp__caption"><div class="pswp__caption__center"></div></div></div></div></div>').appendTo('body')

//销售地图申请提交键绑定
$(document).on('click', 'a#mapapplypost', function(){
    $.mobile.loading('show')
    var self = $(this)
    form = self.parents('form')
    if(form.find(':file')[0].files.length==1&&form.find(':file')[0].files[0].size>1024*1024){
        mymessage('上传文件超过1MB,请重新选择')
        return false
    }
    if(form.find(':file')[0].files.length!=1){
        mymessage('请选择一张图片后再上传')
        return false
    }
    self.addClass('ui-disabled')
    postdata = new FormData(form[0])
    // $.post('manage?action=mapapply', postdata).done(function(data){
        // console.info(data)
    // })
    $.ajax({
        url: 'manage?action=mapapply', 
        type:'POST', 
        data: postdata,
        // cache: false,
        contentType: false,
        processData: false
    }).done(function(data){
        console.info(data)
        if(data=='done'){
            mymessage('申请提交成功,请等候审核')
            location.href="sellmap"
        }else if(data=='notimage'){
            mymessage('您上传的文件不是图片文件,请重新选择图片上传')
            self.removeClass('ui-disabled')
        }else{
            mymessage('未知错误:'+ data)
            self.removeClass('ui-disabled')
        }
    })
})
$(document).on('change', '#map input#file', function(){
    console.info(this)
    if(this.files&&this.files[0]){
        if(this.files[0].size>1024*1024){
            mymessage('上传文件超过1MB,请重新选择')
        }else{
        $('#map div.imgpre img').attr('src', URL.createObjectURL(this.files[0]))}
    }
})
//地图测试加载时loading
$(document).on('pageshow', 'section#map, section#fwquery', function(){
    $.mobile.loading('show')
})

//我要分享按鈕绑定验证
$(document).on('click', '.share a.nosession', function(){
    mymessage('请先登录,再进行分享')
    return false;
})

//点击长按扫码popup
$(document).on('click', '.qr_display', function(){
    var self = $(this)
    var page = self.parents('.ui-page')
    page.find('.popupqr').popup('open')
})

//防伪查询绑定
var fwcode
$(document).on('click', '#fwbutton', function(){
    $.mobile.loading('show', {textVisible:true, text: '防伪码查询中...'})
    $('#fwtojfbutton').hide()
    var self = $(this)
    self.addClass('ui-disabled')
    var code = $('#fwcode').val().replace(/-/g, '')
    if(code.length!=16){
        mymessage('您输入的防伪码位数不对,请查看清楚后重新输入')
        $('#fwcode').focus()
        return false;
    }
    if(code.search(/[^\d]/)!=-1){
        mymessage('您输入的防伪码存在字母,请查看清楚后重新输入')
        $('#fwcode').select()
        return false;
    }
    $.post('manage?action=fwquery&code='+code, null, null, 'json').done(
        function(data){
            $.mobile.loading('hide')
            self.removeClass('ui-disabled').find('.ui-btn-text').text('重新查询')
            // console.info(data)
            var text = data.msg
            /*　此处为防伪码获取积分，暂时省略不用
            if(data.valid){
                fwcode = code
                if(data.status==0){
                    $('#fwtojfbutton').slideDown()
                }else{
                    text += '<hr><div style="color:black">该防伪码已被获取过积分</div>'
                }
            }*/
            $('#fwresult').html(text).slideDown()
    }).fail(function(data){
        self.removeClass('ui-disabled').find('.ui-btn-text').text('重新查询')
        mymessage('未知错误')
    })
})
/*　此处为防伪码获取积分，暂时省略不用
$(document).on('click', '#fwtojfbutton', function(){
    $.mobile.loading('show')
    self = $(this)
    self.addClass('ui-disabled')
    $.post('manage?action=fwtojf', {'code': fwcode}, null, 'json').done(function(data){
        // console.info(data)
        self.removeClass('ui-disabled')
        if(data.status=='done'){
            $.mobile.loading('hide')
            $('#fwresult').html('<div style="text-align:center;color:black;"><img src="'+data.qrurl+'"/><br/>长按二维码或通过<br/>微信客户端扫码获取积分</div>').slideDown()
        }else if(data.status=='already'){
            mymessage('该防伪码已经获取过积分')
        }else{
            mymessage('无此防伪码')
        }
    }).fail(function(data){
        self.removeClass('ui-disabled')
        mymessage('未知错误')
    })
})*/

//downapp微信打开提示
$(document).on('click', '#downapp a[data-icon="android"], #downapp a[data-icon="apple"]', function(){
    var action = $(this).attr('data-icon')
    if(inwx){
        if(UA.match(/Mac\s+OS/i)){
            if(action=='android'){
                var winHeight = $(window).height();
                $(".weixin-tip").css("height",winHeight);
                $(".weixin-tip").show();
                $.post('manage?action=downapp_inwx_appledownanroid_faild')
                return false;
            }else{
                $.post('manage?action=downapp_inwx_success_to_applewebsite')
                // location.href="http://a.app.qq.com/o/simple.jsp?pkgname=com.bluetoothARC"
                location.href="https://itunes.apple.com/cn/app/yin-su-feng-bao/id1043432800"
                return false
            }
        }else if(action=='apple'){
            mymessage('抱歉,您无法在非iOS平台下载iOS版本App')  
            //埋点
            $.post('manage?action=downapp_inwx_androiddownapple_faild');
            return false;
        }
            var winHeight = $(window).height();
            $(".weixin-tip2").css("height",winHeight);
            $(".weixin-tip2").show();
        //location.href= 'http://sj.qq.com/myapp/detail.htm?apkName=com.bluetoothARC'
        //埋点
        $.post('manage?action=downapp_inwx_success_to_QQdown');        
        return false
    }else{
        //埋点
        $.post('manage?action=downapp_success_'+action);
    }
})
//埋点
$(document).on('click', '#popupAndroidDown a', function(){
    $.post('manage?action=downapp_sucessto_' + $(this).attr('appto'));
})
$(document).on('click', '.weixin-tip,.weixin-tip2', function(){
    $(this).hide();
})

//防伪查询二维码扫描
$(document).on('click', '#fwscan', function(){
    wx.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType: ["qrCode"], // 可以指定扫二维码还是一维码，默认二者都有
        success: fwscansucfunc
    });
})
fwscansucfunc = function(res){
    var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
    var codes = result.split('http://wap.xologood-fc.com/yingbaozhineng/fw.html?code=')
    if(codes.length!=2){
        mymessage('抱歉,您所扫描的不是音速风暴的防伪二维码,请重新扫描')
    }else{
        var code = codes[1]
        var newfwvalue = ''
        var i
        for(i=0;i<3;i++){
            newfwvalue += code.slice(i*4, i*4+4) + '-'
        }
        newfwvalue += code.slice(i*4, i*4+4)
        $('#fwcode').val(newfwvalue)                
    }    
}
//分享好友,朋友圈键绑定
$(document).on('click', '.sharewx a', function(){
    $('.weixin-tip2').show()
})
//语言选择
$(document).on('change', '.selectlanguege select', function(){
    console.info(this.value)
    if(this.value==""||this.value=="/en/")
    location.href = location.origin + this.value
})
//feature特点点击时返回页首
$('body').on('pageshow', '#feature.ui-page', function(){
    // console.info('Show')
    $('#feature a.ui-collapsible-heading-toggle').bind('click', function(){
        $('body').scrollTop(0);
    })    
})
$('body').on('pagehide', '#feature.ui-page', function(){
    // console.info('beforehide', this)
    $('#feature a.ui-collapsible-heading-toggle').unbind('click');
})